package com.maixin.code.utils;

import java.util.ArrayList;
import java.util.List;

import com.maixin.code.entity.Menus;

public class MenusUtils {
	/**
	 * 根据查询出来的Menus集合，组成Menus树结构，然后组成EXT树结构字符串返回
	 * @param menuList Menus集合
	 * @return
	 */
	public static String MenusList2Str(List<Menus> menuList){
		List<Menus> meTree = new ArrayList<Menus>();
		StringBuffer strB = new StringBuffer();
		strB.append("new Ext.tree.AsyncTreeNode({id:'root', text:'根节点',");
		for (int i = 0; i < menuList.size(); i++) {
			Menus menus = menuList.get(i);
			List<Menus> temp = new ArrayList<Menus>();
			for (int j = 0; j < menuList.size(); j++) {
				Menus menu = menuList.get(j);
				//当父节点不为空，并且次Id和父节点Id相同的时候，保存
				if(menus.getId().equals(menu.getParentid())){
					temp.add(menu);
					menus.setMenusList(temp);
				}
			}
			if(0 ==menus.getParentid()){
				meTree.add(menus);
			}
		}
		strB = tree2Str(meTree, strB);
		strB.append("})");
		return strB.toString();
		
	}
	/**
	 * 根据Menus的树状结构，拼装成EXT的树结构字符串返回
	 * @param meTree Menus的树状结构List集合
	 * @param strB 拼装的字符串
	 * @return
	 */
	private static StringBuffer tree2Str(List<Menus> meTree,StringBuffer strB){
		strB.append("children:[");
		for (int i = 0; i < meTree.size(); i++) {
			Menus menus = meTree.get(i);
			strB.append("{text:'"+menus.getText()+"',");
			strB.append("leaf:"+menus.getLeaf()+",");
			//如果Url中没有数据，则为父节点，连URL都可以不设置
			if(null == menus.getUrl()){
				strB.append("url:"+menus.getUrl()+"");
			}else{
				strB.append("url:'"+menus.getUrl()+"'");
			}
			//当前的Menus中如果有叶子节点，递归调用收索拼装
			if(null!=menus.getMenusList()){
				strB.append(",");
				tree2Str(menus.getMenusList(), strB);
			}
			strB.append("},");
			//去掉最后一个字符“,”
			if(meTree.size()-1 == i){
				strB.delete(strB.length()-1, strB.length());
			}
		}
		strB.append("]");
		return strB;
	}
}
